package com.test.service.Impl;
import com.test.dao.UserMapper;
import com.test.entity.AuthUser;
import com.test.service.AuthService;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@Service
public class AuthServiceImpl implements AuthService {
    @Resource
    UserMapper userMapper;
    @Transactional
    @Override
    public void register(String name, String sex, String grade, String password) {
        BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
        AuthUser user=new AuthUser(0,name,encoder.encode(password),"user");
        if(userMapper.registerUser(user)<=0){
            throw new RuntimeException("用户信息添加失败");
        }
        if(userMapper.addStudentInfo(user.getId(),name,grade,sex)<=0){
            throw new RuntimeException("学生详细信息添加失败");
        }
    }

    @Override
    public AuthUser findUser(HttpSession session) {
        //HttpSession session=request.getSession();
        AuthUser user=(AuthUser)session.getAttribute("user");
        if(user==null){
            Authentication authentication=SecurityContextHolder.getContext().getAuthentication();
            user=userMapper.getUserByLogin(authentication.getName());
            session.setAttribute("user",user);
        }
        return user;
    }
}
